<template>
  <div class="permission-management">
    <!-- 页面标题和操作按钮 -->
    <div class="page-header">
      <h1>权限管理</h1>
      <div class="header-actions">
        <el-button type="primary" @click="handleAdd">
          <Plus />
          新增权限
        </el-button>
      </div>
    </div>

    <el-row :gutter="20">
      <!-- 左侧：权限列表 -->
      <el-col :span="12">
        <el-card class="permission-list-card">
          <template #header>
            <div class="card-header">
              <span>权限列表</span>
              <div class="header-actions">
                <el-button type="primary" size="small" @click="handleAdd">
                  <el-icon><Plus /></el-icon>
                  新增权限
                </el-button>
                <el-button size="small" @click="refreshPermissions">
                  <el-icon><Refresh /></el-icon>
                  刷新
                </el-button>
              </div>
            </div>
          </template>

          <el-table :data="permissionList" border stripe style="width: 100%" v-loading="loading">
            <el-table-column prop="name" label="权限名称" width="150" />
            <el-table-column prop="resource" label="资源" width="100" />
            <el-table-column prop="action" label="操作" width="100" />
            <el-table-column prop="type" label="类型" width="100">
              <template #default="scope">
                <el-tag :type="getPermissionTypeTag(scope.row.type)" size="small">
                  {{ getPermissionTypeText(scope.row.type) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="isEnabled" label="状态" width="80">
              <template #default="scope">
                <el-tag :type="scope.row.isEnabled ? 'success' : 'danger'" size="small">
                  {{ scope.row.isEnabled ? '启用' : '禁用' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150">
              <template #default="scope">
                <el-button type="primary" size="small" @click="handleEdit(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  size="small"
                  @click="handleDelete(scope.row.id)"
                  style="margin-left: 5px"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>

      <!-- 右侧：角色权限分配 -->
      <el-col :span="12">
        <el-card class="role-permission-card">
          <template #header>
            <div class="card-header">
              <span>角色权限分配</span>
            </div>
          </template>

          <div class="role-permission-content">
            <div class="role-selector">
              <el-select v-model="selectedRoleId" placeholder="请选择角色" @change="onRoleChange">
                <el-option
                  v-for="role in roleList"
                  :key="role.id"
                  :label="role.name"
                  :value="role.id"
                />
              </el-select>
            </div>

            <div v-if="selectedRoleId" class="permission-assignment">
              <div class="assignment-header">
                <h4>为角色分配权限</h4>
                <div class="assignment-actions">
                  <el-button type="primary" size="small" @click="selectAllPermissions">
                    全选
                  </el-button>
                  <el-button type="info" size="small" @click="clearAllPermissions">
                    清空
                  </el-button>
                </div>
              </div>

              <el-tree
                ref="permissionTreeRef"
                :data="permissionTree"
                show-checkbox
                node-key="id"
                :props="treeProps"
                class="permission-tree"
                @check="handleTreeCheck"
              >
                <template #default="{ node, data }">
                  <span class="tree-node">
                    <span class="node-label">{{ node.label }}</span>
                    <el-tag size="small" type="info" class="node-type">
                      {{ data.resource }}:{{ data.action }}
                    </el-tag>
                  </span>
                </template>
              </el-tree>

              <div class="assignment-footer">
                <el-button @click="resetPermissions">重置</el-button>
                <el-button
                  type="primary"
                  @click="saveRolePermissions"
                  :loading="saving"
                  :disabled="!hasChanges"
                >
                  保存分配
                </el-button>
              </div>
            </div>

            <div v-else class="no-role-placeholder">
              <el-empty description="请选择一个角色来分配权限">
                <el-icon size="60" color="#909399">
                  <UserFilled />
                </el-icon>
              </el-empty>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 新增/编辑权限对话框 -->
    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑权限' : '新增权限'" width="500px">
      <el-form
        ref="permissionFormRef"
        :model="permissionForm"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="权限名称" prop="name">
          <el-input v-model="permissionForm.name" placeholder="请输入权限名称" maxlength="50" />
        </el-form-item>
        <el-form-item label="权限描述" prop="description">
          <el-input
            v-model="permissionForm.description"
            placeholder="请输入权限描述（可选）"
            type="textarea"
            rows="3"
          />
        </el-form-item>
        <el-form-item label="资源标识" prop="resource">
          <el-input v-model="permissionForm.resource" placeholder="如：user, role, menu" />
        </el-form-item>
        <el-form-item label="操作类型" prop="action">
          <el-select v-model="permissionForm.action" placeholder="请选择操作类型">
            <el-option label="查看" value="read" />
            <el-option label="创建" value="create" />
            <el-option label="编辑" value="update" />
            <el-option label="删除" value="delete" />
            <el-option label="导出" value="export" />
            <el-option label="导入" value="import" />
          </el-select>
        </el-form-item>
        <el-form-item label="权限类型" prop="type">
          <el-select v-model="permissionForm.type" placeholder="请选择权限类型">
            <el-option label="菜单权限" :value="1" />
            <el-option label="功能权限" :value="2" />
            <el-option label="数据权限" :value="3" />
            <el-option label="API权限" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="sortOrder">
          <el-input-number v-model="permissionForm.sortOrder" :min="0" :max="999" />
        </el-form-item>
        <el-form-item label="状态" prop="isEnabled">
          <el-switch v-model="permissionForm.isEnabled" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Refresh, UserFilled } from '@element-plus/icons-vue'
import { roleApi, permissionApi } from '@/api'

// 响应式数据
const permissionList = ref([])
const roleList = ref([])
const permissionTree = ref([])
const selectedRoleId = ref('')
const selectedPermissionIds = ref([])
const originalPermissionIds = ref([])
const loading = ref(false)
const saving = ref(false)
const dialogVisible = ref(false)
const isEdit = ref(false)
const currentPermissionId = ref('')

// 模板引用
const permissionTreeRef = ref(null)
const permissionFormRef = ref(null)

// 表单数据
const permissionForm = reactive({
  name: '',
  description: '',
  resource: '',
  action: '',
  type: 2,
  sortOrder: 0,
  isEnabled: true,
})

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入权限名称', trigger: 'blur' },
    { max: 50, message: '权限名称不能超过50个字符', trigger: 'blur' },
  ],
  resource: [{ required: true, message: '请输入资源标识', trigger: 'blur' }],
  action: [{ required: true, message: '请选择操作类型', trigger: 'change' }],
  type: [{ required: true, message: '请选择权限类型', trigger: 'change' }],
}

// 树形组件配置
const treeProps = {
  label: 'name',
  children: 'children',
}

// 计算属性
const hasChanges = computed(() => {
  if (!selectedRoleId.value) return false
  const original = new Set(originalPermissionIds.value)
  const current = new Set(selectedPermissionIds.value)

  if (original.size !== current.size) return true

  for (const id of original) {
    if (!current.has(id)) return true
  }

  for (const id of current) {
    if (!original.has(id)) return true
  }

  return false
})

// 生命周期
onMounted(async () => {
  await Promise.all([fetchPermissions(), fetchRoles(), fetchPermissionTree()])
})

// 获取权限列表
const fetchPermissions = async () => {
  loading.value = true
  try {
    console.log('开始获取权限列表...')
    const res = await permissionApi.getAllPermissions()
    console.log('权限API响应:', res)
    // http.js已经返回了response.data，所以res本身就是数据
    permissionList.value = res || []
    console.log('权限列表数据:', permissionList.value)
  } catch (err) {
    console.error('获取权限列表失败:', err)
    console.error('错误详情:', {
      message: err.message,
      response: err.response?.data,
      status: err.response?.status,
    })

    ElMessage.error('获取权限列表失败：' + (err.response?.data?.message || err.message))
  } finally {
    loading.value = false
  }
}

// 获取角色列表
const fetchRoles = async () => {
  try {
    console.log('获取角色列表...')
    const res = await roleApi.getAllRoles()
    console.log('角色API响应:', res)

    // http.js已经返回了response.data，所以res本身就是数据
    roleList.value = res || []
    console.log('角色列表数据:', roleList.value)
  } catch (err) {
    console.error('获取角色列表失败:', err)
    ElMessage.error('获取角色列表失败：' + (err.response?.data?.message || err.message))
  }
}

// 获取权限树
const fetchPermissionTree = async () => {
  try {
    console.log('获取权限树...')
    const res = await permissionApi.getPermissionTree()
    console.log('权限树API响应:', res)

    // http.js已经返回了response.data，所以res本身就是数据
    permissionTree.value = res || []
    console.log('权限树数据:', permissionTree.value)

    // 权限树加载完成后，如果已经选择了角色，重新设置勾选状态
    await nextTick()
    if (selectedRoleId.value && selectedPermissionIds.value.length > 0 && permissionTreeRef.value) {
      console.log('权限树加载完成，重新设置勾选状态:', selectedPermissionIds.value)
      permissionTreeRef.value.setCheckedKeys(selectedPermissionIds.value)
    }
  } catch (err) {
    console.error('获取权限树失败:', err)
    ElMessage.error('获取权限树失败：' + (err.response?.data?.message || err.message))
  }
}

// 角色选择变化
const onRoleChange = async (roleId) => {
  console.log('角色切换:', { roleId, oldRole: selectedRoleId.value })

  if (!roleId) {
    selectedPermissionIds.value = []
    originalPermissionIds.value = []
    return
  }

  try {
    console.log('获取角色权限:', roleId)
    const res = await permissionApi.getPermissionsByRole(roleId)
    console.log('角色权限API响应:', res)

    // http.js已经返回了response.data，所以res本身就是数据
    const permissions = res || []
    console.log('解析的权限数据:', permissions)

    const permissionIds = permissions.map((p) => p.id)
    console.log('权限ID列表:', permissionIds)

    selectedPermissionIds.value = permissionIds
    originalPermissionIds.value = [...selectedPermissionIds.value]

    await nextTick()
    if (permissionTreeRef.value) {
      console.log('设置树形控件勾选状态:', selectedPermissionIds.value)
      permissionTreeRef.value.setCheckedKeys(selectedPermissionIds.value)
    } else {
      console.error('permissionTreeRef为空')
    }
  } catch (err) {
    console.error('获取角色权限失败:', err)
    ElMessage.error('获取角色权限失败：' + (err.response?.data?.message || err.message))
  }
}

// 树形选择变化
const handleTreeCheck = (data, { checkedKeys, checkedNodes }) => {
  console.log('权限树勾选变化:', {
    checkedKeys,
    checkedNodesCount: checkedNodes?.length,
    data: data,
  })
  selectedPermissionIds.value = checkedKeys
}

// 全选权限
const selectAllPermissions = () => {
  const getAllKeys = (nodes) => {
    const keys = []
    nodes.forEach((node) => {
      keys.push(node.id)
      if (node.children && node.children.length > 0) {
        keys.push(...getAllKeys(node.children))
      }
    })
    return keys
  }

  const allKeys = getAllKeys(permissionTree.value)
  selectedPermissionIds.value = allKeys

  if (permissionTreeRef.value) {
    permissionTreeRef.value.setCheckedKeys(allKeys)
  }
}

// 清空权限
const clearAllPermissions = () => {
  selectedPermissionIds.value = []
  if (permissionTreeRef.value) {
    permissionTreeRef.value.setCheckedKeys([])
  }
}

// 重置权限
const resetPermissions = () => {
  selectedPermissionIds.value = [...originalPermissionIds.value]
  if (permissionTreeRef.value) {
    permissionTreeRef.value.setCheckedKeys(originalPermissionIds.value)
  }
}

// 保存角色权限
const saveRolePermissions = async () => {
  if (!selectedRoleId.value) {
    ElMessage.warning('请先选择一个角色')
    return
  }

  console.log('保存角色权限:', {
    roleId: selectedRoleId.value,
    selectedPermissions: selectedPermissionIds.value,
    originalPermissions: originalPermissionIds.value,
  })

  try {
    saving.value = true
    const result = await permissionApi.assignToRole(
      selectedRoleId.value,
      selectedPermissionIds.value,
    )
    console.log('权限分配API响应:', result)

    // 更新原始权限状态
    originalPermissionIds.value = [...selectedPermissionIds.value]
    console.log('权限分配成功，更新状态:', {
      newOriginal: originalPermissionIds.value,
      current: selectedPermissionIds.value,
    })

    ElMessage.success('权限分配保存成功')
  } catch (err) {
    console.error('权限分配保存失败:', err)
    ElMessage.error('权限分配保存失败：' + (err.response?.data?.message || err.message))
  } finally {
    saving.value = false
  }
}

// 新增权限
const handleAdd = () => {
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
}

// 编辑权限
const handleEdit = (row) => {
  isEdit.value = true
  currentPermissionId.value = row.id
  Object.assign(permissionForm, {
    name: row.name,
    description: row.description || '',
    resource: row.resource,
    action: row.action,
    type: row.type,
    sortOrder: row.sortOrder,
    isEnabled: row.isEnabled,
  })
  dialogVisible.value = true
}

// 删除权限
const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除该权限吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    await permissionApi.deletePermission(id)
    ElMessage.success('权限删除成功')
    await fetchPermissions()
    await fetchPermissionTree()
  } catch (err) {
    if (err !== 'cancel') {
      ElMessage.error('删除失败：' + (err.response?.data?.message || err.message))
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    await permissionFormRef.value.validate()

    if (isEdit.value) {
      await permissionApi.updatePermission(currentPermissionId.value, permissionForm)
      ElMessage.success('权限更新成功')
    } else {
      await permissionApi.createPermission(permissionForm)
      ElMessage.success('权限创建成功')
    }

    dialogVisible.value = false
    await Promise.all([fetchPermissions(), fetchPermissionTree()])
  } catch (err) {
    if (err.name !== 'ValidationError') {
      ElMessage.error('操作失败：' + (err.response?.data?.message || err.message))
    }
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(permissionForm, {
    name: '',
    description: '',
    resource: '',
    action: '',
    type: 2,
    sortOrder: 0,
    isEnabled: true,
  })
  if (permissionFormRef.value) {
    permissionFormRef.value.resetFields()
  }
}

// 刷新权限
const refreshPermissions = async () => {
  await Promise.all([fetchPermissions(), fetchPermissionTree()])
  ElMessage.success('权限列表已刷新')
}

// 获取权限类型标签
const getPermissionTypeTag = (type) => {
  const typeMap = {
    1: 'primary',
    2: 'success',
    3: 'warning',
    4: 'info',
  }
  return typeMap[type] || 'info'
}

// 获取权限类型文本
const getPermissionTypeText = (type) => {
  const typeMap = {
    1: '菜单',
    2: '功能',
    3: '数据',
    4: 'API',
  }
  return typeMap[type] || '未知'
}
</script>

<style scoped>
.permission-management {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.page-description {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.permission-list-card,
.role-permission-card {
  height: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.role-permission-content {
  min-height: 500px;
}

.role-selector {
  margin-bottom: 20px;
}

.permission-assignment {
  border-top: 1px solid #e4e7ed;
  padding-top: 20px;
}

.assignment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.assignment-header h4 {
  margin: 0;
  color: #303133;
}

.assignment-actions {
  display: flex;
  gap: 8px;
}

.permission-tree {
  max-height: 300px;
  overflow-y: auto;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  padding: 12px;
  margin-bottom: 20px;
}

.tree-node {
  display: flex;
  align-items: center;
  gap: 8px;
}

.node-label {
  flex: 1;
}

.node-type {
  font-size: 10px;
}

.assignment-footer {
  display: flex;
  justify-content: center;
  gap: 12px;
  padding-top: 16px;
  border-top: 1px solid #e4e7ed;
}

.no-role-placeholder {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
}
</style>
